﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Douban.Core;
using Douban.Modules.Info.ViewModels;
using Douban.Modules.Info.Views;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Composite.Events;
using Douban.Core.Events;
using Douban.Core.Menus;
using Microsoft.Practices.Composite.Presentation.Commands;

namespace Douban.Modules.Info
{
    public class InfoModule : IModule
    {
        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;
        private readonly IMenuManager _menuManager;
        private InfoController _infoController;

        public InfoModule(
            IUnityContainer container, 
            IRegionManager regionManager, 
            IMenuManager menuManager)
        {
            _container = container;
            _regionManager = regionManager;
            _menuManager = menuManager;
        }

        public void Initialize()
        {
            Register();
            RegisterMenu();
        }

        private void Register()
        {
            _container
                .RegisterType<InfoController>(new ContainerControlledLifetimeManager())
                .RegisterType<IHeaderView, HeaderView>()
                .RegisterType<IUserInfoView, UserInfoView>()
                .RegisterType<IHeaderViewModel, HeaderViewModel>()
                .RegisterType<IUserInfoViewModel, UserInfoViewModel>();

            _infoController = _container.Resolve<InfoController>();

            _regionManager.RegisterViewWithRegion(RegionNames.HeaderRegion,
                () => _container.Resolve<IHeaderViewModel>().View);

            _container.Resolve<IEventAggregator>().GetEvent<CheckInfoEvent>().Subscribe(CheckInfo);
        }

        private void RegisterMenu()
        {
            MenuItem menuItem = new MenuItem 
            { 
                Name = "个人信息",
                Icon = "pack://application:,,,/Douban.Modules.Info;Component/Images/chat.png",
                Command = new DelegateCommand<object>(obj => _infoController.CheckInfo())
            };

            IMenuManager _menuManager = _container.Resolve<IMenuManager>();
            _menuManager.Add(menuItem);
        }

        private void CheckInfo(string userId)
        {
            _infoController.CheckInfo(userId);
        }
    }
}
